/*
 * Copyright (C) 2023 KylinSoft Co., Ltd.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */
#include "tinycountdown.h"
//#include "ui_tinycountdown.h"
#include "theme.h"
#include <QBitmap>
#include "utils.h"
extern void qt_blurImage(QImage &blurImage, qreal radius, bool quality, int transposed);
tinyCountdown::tinyCountdown(QWidget *parent) :
    QWidget(parent)
{
    setupUi(this);

    clockIcon = new QLabel(this);
    clockIcon->setFixedSize(24,24);

    timeLabel = new QLabel(this);
    timeLabel->setAlignment(Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter);

    suspendRunBtn = new RoundBtn(this);
    suspendRunBtn->setEnabled(true);

    finishBtn = new RoundBtn(this);
    finishBtn->setEnabled(true);

    mainBtn = new QPushButton(this);
    mainBtn->setEnabled(true);

    closeBtn = new QPushButton(this);

    //右上角关闭
    closeStyle();
    switchStyle();
    suspendRunBtnStyle();
    finishBtnStyle();
    connect(closeBtn, SIGNAL(clicked()), this, SLOT(set_dialog_close()) );
    //左上闹钟图标
    clockIcon->setPixmap(QIcon::fromTheme("kylin-alarm-clock").pixmap(24,24));
   //闹钟时间字体改为灰色
   QPalette pa;
   pa.setColor(QPalette::WindowText,Qt::gray);
   //主窗口connect
   connect(mainBtn, SIGNAL(clicked()), this, SLOT(showMainWindow()) );
   //显示，但不可移动
   settingsStyle();
   updateWidgetRadius();
   bool onTablet = GsettingSubject::getInstance()->getOnTablet();
   updatePosition(onTablet);
}


void tinyCountdown::updateWidgetRadius()
{

    this->setAttribute(Qt::WA_TranslucentBackground);//设置窗口背景透明
    // 添加窗管协议
//    XAtomHelper::setStandardWindowHint(this->winId());
//    kdk::UkuiStyleHelper::self()->removeHeader(this);
    //圆角
#ifdef onTooltip
    QBitmap bmp(this->size());
    bmp.fill();
    QPainter p(&bmp);
    p.setRenderHint(QPainter::Antialiasing);  // 反锯齿;
    p.setPen(Qt::NoPen);
    p.setBrush(palette().color(QPalette::Base));
    p.drawRoundedRect(bmp.rect(),WINDOWN_RADIUS,WINDOWN_RADIUS);
    setMask(bmp);
#endif
}

void tinyCountdown::showThisWindow()
{
    kdk::UkuiStyleHelper::self()->removeHeader(this);
    this->show();
}

tinyCountdown::~tinyCountdown()
{
//    delete ui;
}

void tinyCountdown::setupUi(QWidget *tinyCountdown)
{
    if (tinyCountdown->objectName().isEmpty())
        tinyCountdown->setObjectName(QString::fromUtf8("tinyCountdown"));
    tinyCountdown->resize(320, 50);

    retranslateUi(tinyCountdown);

    QMetaObject::connectSlotsByName(tinyCountdown);
}// setupUi

void tinyCountdown::retranslateUi(QWidget *tinyCountdown)
{
    tinyCountdown->setWindowTitle(QApplication::translate("tinyCountdown", "tinyCountdown", nullptr));
} // retranslateUi

/**
 * @brief 显示倒计时时间
 */
void tinyCountdown::updateTimeInfo(QString str)
{
    timeLabel->setText(str);
    timeLabel->setAlignment(Qt::AlignVCenter);
}


/*
void tinyCountdown::focusOutEvent(QFocusEvent *event)
{
    qDebug()<<"dbq-"<<"focusOutEvent";
}

void tinyCountdown::focusInEvent(QFocusEvent *event)
{
    qDebug()<<"dbq-"<<"focusInEvent";
}
*/
#ifdef onTooltip
// 在鼠标光标在小部件内部时按下鼠标按钮时调用，或者当小部件使用grabMouse ()抓住鼠标时调用。按下鼠标而不释放它实际上与调用grabMouse ()相同。
void tinyCountdown::mousePressEvent(QMouseEvent *event)
{
    if (event->button() == Qt::LeftButton) {
        this->dragPosition = event->globalPos() - frameGeometry().topLeft();
        this->mousePressed = true;
    }
    QWidget::mousePressEvent(event);
}
//在鼠标按钮被释放时被调用。当小部件接收到相应的鼠标按下事件时，它就会接收鼠标释放事件。这意味着如果用户在您的小部件内按下鼠标，然后在释放鼠标按钮之前将鼠标拖动到其他地方，您的小部件将收到释放事件。
void tinyCountdown::mouseReleaseEvent(QMouseEvent *event)
{

    if (event->button() == Qt::LeftButton) {
        this->mousePressed = false;
    }

    QWidget::mouseReleaseEvent(event);
    this->setCursor(Qt::ArrowCursor);
}
//每当鼠标移动而按住鼠标按钮时调用。这在拖放操作期间很有用。
void tinyCountdown::mouseMoveEvent(QMouseEvent *event)
{
    if (this->mousePressed) {
        move(event->globalPos() - this->dragPosition);
        this->setCursor(Qt::ClosedHandCursor);
    }
    QWidget::mouseMoveEvent(event);
}
#endif


void tinyCountdown::closeEvent(QCloseEvent *event)
{
    event->ignore();//忽视
    this->set_dialog_close();
}

void tinyCountdown::paintEvent(QPaintEvent * event)
{
#ifdef onTooltip
    Q_UNUSED(event);
    QPainter p(this);
    p.setRenderHint(QPainter::Antialiasing);
    QPainterPath rectPath;
    rectPath.addRoundedRect(this->rect().adjusted(SHADOW_RANGE, SHADOW_RANGE, -SHADOW_RANGE, -SHADOW_RANGE), WINDOWN_RADIUS, WINDOWN_RADIUS);
    // 画一个黑底
    QPixmap pixmap(this->rect().size());
    pixmap.fill(Qt::transparent);
    QPainter pixmapPainter(&pixmap);
    pixmapPainter.setRenderHint(QPainter::Antialiasing);
    auto shadowColor = palette().text().color();
    shadowColor.setAlphaF(SHADOWCOLOR_ALPHAF);
    pixmapPainter.setBrush(shadowColor);
    pixmapPainter.setPen(Qt::transparent);
    pixmapPainter.drawPath(rectPath);
    pixmapPainter.end();
    // 模糊这个黑底
    QImage img = pixmap.toImage();
    qt_blurImage(img, VAGUE_RADIUS, false, false);
    // 挖掉中心
    pixmap = QPixmap::fromImage(img);
    QPainter pixmapPainter2(&pixmap);
    pixmapPainter2.setRenderHint(QPainter::Antialiasing);
    pixmapPainter2.setCompositionMode(QPainter::CompositionMode_Clear);
    pixmapPainter2.setPen(Qt::transparent);
    pixmapPainter2.setBrush(Qt::transparent);
    pixmapPainter2.drawPath(rectPath);
    // 绘制阴影
    p.drawPixmap(this->rect(), pixmap, pixmap.rect());
    QStyleOption opt;
    opt.init(this);
    // 绘制一个背景
    p.save();
    //描边
    QColor borderColor = palette().text().color();
    borderColor.setAlphaF(BORDERCOLOR_ALPHAF);
    p.setPen(borderColor);
    p.translate(BORDER_RANGE, BORDER_RANGE);
    p.setBrush(palette().color(QPalette::Base));
    p.drawPath(rectPath);
    p.restore();
#else
    Q_UNUSED(event);
    QPainter p(this);
    p.setRenderHint(QPainter::Antialiasing);  // 反锯齿;
    //绘制器路径
    QPainterPath rectPath;
    rectPath.addRect(this->rect());
    p.fillPath(rectPath,palette().color(QPalette::Base));
#endif
}




/**
 * @brief 清空数据
 */
void tinyCountdown::clearData()
{
    timeLabel->setText("00:00:00");
    this->set_dialog_close();
    updateOnRunState(true);
}



void tinyCountdown::set_dialog_close()
{
    this->hide();
}

void tinyCountdown::showMainWindow()
{
    this->set_dialog_close();
    emit mainWindowClick();
}



void tinyCountdown::showTop()
{
    this->set_dialog_close();
    this->update();
    this->show();
}

void tinyCountdown::updateOnRunState(int onRun)
{
    m_onRun = onRun;
    suspendRunBtnIcon(theme::themetype);
}







void tinyCountdown::settingsStyle()
{
    GsettingSubject * subject = GsettingSubject::getInstance();;
    connect(subject,&GsettingSubject::blackStyle, this,[=](){
        this->blackStyle();
    });
    connect(subject,&GsettingSubject::whiteStyle, this,[=](){
        this->whiteStyle();
    });
    connect(subject,&GsettingSubject::iconChnaged, this,[=](){
        clockIcon->setPixmap(QIcon::fromTheme("kylin-alarm-clock").pixmap(24,24));
    });
    connect(subject,&GsettingSubject::tabletModeChange, this,[=](bool currentTablet){
        updatePosition(currentTablet);
    });
    subject->iniWidgetStyle();
    subject->iniTabletMode();
}

void tinyCountdown::whiteStyle()
{
    mainBtn->setIcon(QIcon(":image/miniIcon/restore_active-w.png"));
    finishBtnIcon(0);
    suspendRunBtnIcon(0);
}

void tinyCountdown::blackStyle()
{
    mainBtn->setIcon(QIcon(":image/miniIcon/restore-active-b.png"));
    finishBtnIcon(1);
    suspendRunBtnIcon(1);
}
void tinyCountdown::closeStyle()
{
    closeBtn->setToolTip(tr("close"));
    closeBtn->setIcon(QIcon::fromTheme("window-close-symbolic"));
    closeBtn->setProperty("isWindowButton", 0x2);
    closeBtn->setProperty("useIconHighlightEffect", 0x8);
    closeBtn->setFlat(true);
}
void tinyCountdown::switchStyle()
{
    mainBtn->setToolTip(tr("main window"));
    mainBtn->setProperty("useButtonPalette", true);
    mainBtn->setIcon(QIcon(":image/miniIcon/restore_active-w.png"));
//    mainBtn->setIconSize(QSize(24,24));
    //手动改成透明色
    Utils::setBtnBackgroundColorTransparent(mainBtn);
}
/**
 * @brief 暂停运行按钮样式
 */
void tinyCountdown::suspendRunBtnStyle()
{
    suspendRunBtn->setToolTip(tr("suspend"));
//    suspendRunBtn->setRadius(14);
    suspendRunBtn->setRadius(28);
    suspendRunBtn->setFlag(RoundBtn::ICON_FLAG);
//    suspendRunBtn->setIconSize(QSize(32,32));
    QColor defaultColor = QColor(0, 0, 0, 0);
    suspendRunBtn->setBtnColor(defaultColor,defaultColor,defaultColor);
    //初始化是运行中
    m_onRun = true;
    suspendRunBtnIcon(theme::themetype);
    connect(suspendRunBtn,&QPushButton::clicked,this,[=](){
        m_onRun = !m_onRun;
        suspendRunBtnIcon(theme::themetype);
        emit suspendClick(m_onRun);
    });
}

void tinyCountdown::finishBtnStyle()
{
    finishBtn->setToolTip(tr("finish"));
//    finishBtn->setRadius(12);
    finishBtn->setRadius(24);
    finishBtn->setFlag(RoundBtn::ICON_FLAG);
//    finishBtn->setIconSize(QSize(28,28));
    QColor defaultColor = QColor(0, 0, 0, 0);
    finishBtn->setBtnColor(defaultColor,defaultColor,defaultColor);
    finishBtnIcon(theme::themetype);
    connect(finishBtn,&QPushButton::clicked,this,[=](){
        emit finishClick();
    });

}

void tinyCountdown::finishBtnIcon(int themeStatus)
{
    if(themeStatus==0){
        finishBtn->setAllIconPatn(":image/miniIcon/finish-light-normal.png"
                                      ,":image/miniIcon/finish-light-hover.png"
                                      ,":image/miniIcon/finish-light-click.png");
    }else{
        finishBtn->setAllIconPatn(":image/miniIcon/finish-dark-normal.png"
                                      ,":image/miniIcon/finish-dark-hover.png"
                                      ,":image/miniIcon/finish-dark-click.png");
    }
}

void tinyCountdown::suspendRunBtnIcon(int themeStatus)
{
    qDebug()<<"dbq-m_onRun"<<m_onRun;
    if(m_onRun){
        if(themeStatus==0){
            suspendRunBtn->setAllIconPatn(":image/miniIcon/suspend-normal-light.png"
                                              ,":image/miniIcon/suspend-hover-light.png"
                                              ,":image/miniIcon/suspend-click-light.png");
        }else{
            suspendRunBtn->setAllIconPatn(":image/miniIcon/suspend-normal-dark.png"
                                              ,":image/miniIcon/suspend-hover-dark.png"
                                              ,":image/miniIcon/suspend-click-dark.png");
        }
    }else{
        if(themeStatus==0){
            suspendRunBtn->setAllIconPatn(":image/miniIcon/start-normal-light.png"
                                              ,":image/miniIcon/start-hover-light.png"
                                              ,":image/miniIcon/start-hover-light.png");
        }else{
            suspendRunBtn->setAllIconPatn(":image/miniIcon/start-normal-dark.png"
                                              ,":image/miniIcon/start-hover-dark.png"
                                              ,":image/miniIcon/start-hover-dark.png");
        }
    }
}

void tinyCountdown::updatePosition(bool onTbalet)
{
    if(onTbalet){
        this->setFixedSize(498,80);
        clockIcon->move(16,28);
        timeLabel->move(52,18);
        QFont font;
        font.setPointSize(36);
        timeLabel->setFont(font);
        timeLabel->setFixedSize(200,44);
        suspendRunBtn->move(262,12);
        suspendRunBtn->setFixedSize(56,56);
        suspendRunBtn->setIconSize(QSize(56, 56));
        finishBtn->move(331,16);
        finishBtn->setFixedSize(48,48);
        finishBtn->setIconSize(QSize(48, 48));
        mainBtn->move(396,16);
        mainBtn->setFixedSize(48,48);
        mainBtn->setIconSize(QSize(48, 48));
        closeBtn->move(444,16);
        closeBtn->setFixedSize(48,48);
        closeBtn->setIconSize(QSize(48, 48));
    }else{
        this->setFixedSize(320,50);
        clockIcon->move(20,13);
        timeLabel->move(52,9);
        QFont font;
        font.setPointSize(18);
        timeLabel->setFont(font);
        timeLabel->setFixedSize(94,32);
        suspendRunBtn->move(154,9);
        suspendRunBtn->setFixedSize(32,32);
        suspendRunBtn->setIconSize(QSize(32, 32));
        finishBtn->move(194,11);
        finishBtn->setFixedSize(28,28);
        finishBtn->setIconSize(QSize(28, 28));
        mainBtn->move(248,13);
        mainBtn->setFixedSize(24,24);
        mainBtn->setIconSize(QSize(16, 16));
        closeBtn->move(280,13);
        closeBtn->setFixedSize(24,24);
        closeBtn->setIconSize(QSize(16, 16));
    }
}




